<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { useSettlementStore, useCustomerStore, useDictStore } from '@/store';
  import { useRoute } from 'vue-router';
  import dayjs from 'dayjs';

  const customerPickerRef = ref();
  const settlementStore = useSettlementStore();
  const customerStore = useCustomerStore();
  const dictStore = useDictStore();
  const route = useRoute();
  const list = ref<any>([]);
  const customers = ref<any>([]);
  const settlement = ref<any>({});

  async function fetchList() {
    return await settlementStore.getSettlementCustomers({
      settlementId: route.params.id,
    });
  }

  async function fetchCustomers() {
    const settlementCustomers = await fetchList();
    customers.value = await customerStore.getCustomers({
      salesId: settlement.value.salesId,
      statusValue: '4',
    });
    list.value = customers.value.map((item: any) => {
      const finded = settlementCustomers.find((i: any) => i.customerId === item.id);
      if (finded) {
        return Object.assign(item, finded);
      }
      // return {
      //   id: finded?.id,
      //   settlementId: settlement.value.id,
      //   customerId: item.id,
      //   customerName: item.companyName,
      //   electricity: settlementCustomers.find((i: any) => i.customerId === item.id)?.electricity,
      //   amount: settlementCustomers.find((i: any) => i.customerId === item.id)?.amount,
      // };
    });
    // if (list.value.length === 0) {
    //   list.value = customers.value.map((item: any) => {
    //     return {
    //       settlementId: settlement.value.id,
    //       customerId: item.id,
    //       customerName: item.companyName,
    //       electricity: 0,
    //       amount: 0,
    //     };
    //   });
    // }
  }

  // function handleAdd() {
  //   customerPickerRef.value.show();
  // }

  async function handleCustomerSelect(customer: any) {
    await settlementStore.saveSettlementCustomer({
      settlement_id: route.params.id,
      customerId: customer.id,
      customerName: customer.companyName,
      amount: 0,
      electricity: 0,
    });
    await fetchList();
    customerPickerRef.value.hide();
  }

  async function handleSave() {
    await settlementStore.saveSettlement({
      id: settlement.value.id,
      amount: settlement.value.amount,
      electricityTotal: settlement.value.electricityTotal,
      customers: [...list.value],
    });
    fetchList();
  }

  function handleViewInvoice() {
    window.open(settlement.value.invoiceUrl);
  }

  async function handleRemove(record: any) {
    await settlementStore.deleteSettlementCustomer({
      id: record.id,
    });
    fetchList();
  }

  onMounted(async () => {
    await fetchList();
    settlement.value = await settlementStore.getSettlement({ id: Number(route.params.id) });
    await fetchCustomers();
  });

  async function handlePass() {
    await settlementStore.saveSettlement({
      id: settlement.value.id,
      invoiceStatusValue: dictStore.value('InvoiceStatus', 'Pass'),
    });
  }

  async function handleNoPass() {
    await settlementStore.saveSettlement({
      id: settlement.value.id,
      invoiceStatusValue: dictStore.value('InvoiceStatus', 'NoPass'),
    });
  }

  function handleAmountChange() {
    let total = 0;
    for (let i = 0; i < list.value.length; i++) {
      total += list.value[i].amount;
    }
    settlement.value.amount = total.toFixed(2);
  }

  function handleElectricityChange() {
    let total = 0;
    for (let i = 0; i < list.value.length; i++) {
      total += list.value[i].electricity;
    }
    settlement.value.electricityTotal = total.toFixed(4);
  }
</script>

<template>
  <div class="container">
    <breadcrumb :items="['menu.finance.management', 'menu.finance.settlement', 'menu.finance.settlement.detail']" />
    <a-card :title="'结算月份：' + dayjs(settlement.tradeMonth).format('YYYY月MM日')">
      <a-space style="margin-bottom: 16px">
        <!-- <a-button type="primary" size="small" @click="handleAdd">新增客户</a-button> -->
        <a-button type="primary" size="mini" @click="handleSave">保存</a-button>
        <a-button type="primary" size="mini" :disabled="settlement.invoiceUrl === null" @click="handleViewInvoice">查看发票</a-button>
        <a-popconfirm content="请选择发票是否通过？" cancel-text="不通过" ok-text="通过" @ok="handlePass" @cancel="handleNoPass">
          <a-button type="primary" size="mini">审核发票</a-button>
        </a-popconfirm>
      </a-space>
      <a-descriptions layout="inline-vertical" bordered style="margin-bottom: 16px">
        <a-descriptions-item label="本期总收益(元)">
          {{ settlement.amount }}
          <!-- <a-input-number style="margin-top: 16px" :default-value="0" :precision="2" v-model="settlement.amount" /> -->
        </a-descriptions-item>
        <a-descriptions-item label="本期总电量(kwh)">
          {{ settlement.electricityTotal }}
          <!-- <a-input-number style="margin-top: 16px" :default-value="0" :precision="4" v-model="settlement.electricityTotal" /> -->
        </a-descriptions-item>
      </a-descriptions>
      <a-table row-key="id" :data="list" :pagination="false">
        <template #columns>
          <a-table-column title="序号" :width="150">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="客户公司" data-index="customerName">
            <template #cell="{ record }">
              <a-input v-model="record.customerName" />
            </template>
          </a-table-column>
          <a-table-column title="电量总额(万千瓦时)" data-index="electricity" :width="200">
            <template #cell="{ record }">
              <a-input-number v-model="record.electricity" :precision="4" @change="handleElectricityChange" />
            </template>
          </a-table-column>
          <a-table-column title="收益总额(元)" data-index="amount" :width="200">
            <template #cell="{ record }">
              <a-input-number v-model="record.amount" :precision="2" @change="handleAmountChange" />
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="60">
            <template #cell="{ record }">
              <a-button type="primary" status="danger" size="small" @click="handleRemove(record)">移除</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <!-- <customer-picker ref="customerPickerRef" @select="handleCustomerSelect" /> -->
  </div>
</template>

<style lang="less" scoped>
  .container {
    padding: 0 16px;
  }
</style>
